//
//  ChatPureRightCell.swift
//  app_rn_frontend
//
//  Created by wanghui on 2018/5/31.
//  Copyright © 2018年 Facebook. All rights reserved.
//

import UIKit
import Kingfisher
import SnapKit
import AudioToolbox

class ChatPureRightCell: ChatBaseCell {
    
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var createTimelabel: WHLabel!
    
    @IBOutlet weak var avatar: UIImageView!
    
    @IBOutlet weak var namelabel: UILabel!
    
    @IBOutlet weak var contentTextview: UITextView!
    
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    @IBOutlet weak var bubble: UIImageView!
    
    lazy var blurView:UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.isHidden = true
        return view
    }()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.contentTextview.delegate = self
        self.backgroundColor = UIColor.clear
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        let resend = UITapGestureRecognizer.init(target: self, action: #selector(resendMsg))
        self.sendfailureBtn.addGestureRecognizer(resend)
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
        
        self.bubble.addSubview(self.contentTextview)
        self.bubble.isUserInteractionEnabled = true
        
        self.contentTextview.delaysContentTouches = false
        self.addLongPress()
    }
    
    //长按手势
    @objc func addLongPress() {
        let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressView(_:)))
        //长按等待时间
        longPressGes.minimumPressDuration = 0.5
        
        //长按时候,手指头可以移动的距离
        longPressGes.allowableMovement = 30
        self.bubble.isUserInteractionEnabled = true
//        self.bubble.addGestureRecognizer(longPressGes)
        self.contentTextview.addGestureRecognizer(longPressGes)
    }
    
    @objc func longPressView(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == .began {
            //短振动，普通短震，3D Touch 中 Peek 震动反馈
            let soundShort = SystemSoundID(1519)

//            //普通短震，3D Touch 中 Pop 震动反馈,home 键的振动
            let soundMiddle = SystemSoundID(1520)
//
//            // 连续三次短震
//            let soundThere = SystemSoundID(1521)

            //执行震动
            AudioServicesPlaySystemSound(soundMiddle)
            
            
            
            //长按手势开启
            self.addMenuItem()
            self.contentTextview.becomeFirstResponder()
            self.contentTextview.selectedTextRange = self.contentTextview.textRange(from: self.contentTextview.beginningOfDocument, to: self.contentTextview.endOfDocument)
        }else {
            
        }
    }
    
    //长按头像实现@功能
    @objc func avatarAddLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(avatarLongPress(_:)))
        longPressGes.minimumPressDuration = 0.5
        
        longPressGes.allowableMovement = 30
        self.avatar.isUserInteractionEnabled = true
        self.avatar.addGestureRecognizer(longPressGes)
    }
    
    @objc func avatarLongPress(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势添加@
            self.delegate?.addAtInTextviewDelegate(msg: model)
        }else {
            
        }
    }
    
    @objc func tapSelector() {
        print("点击了头像")
//        transition()
    }
    
    @objc func resendMsg() {
        self.model.status = .pending
        self.layoutSubviews()
        self.delegate?.resend(self.model,cell:self)
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        if let avatar = model.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        } else {
            self.avatar.image = #imageLiteral(resourceName:"defaultAvatar")
        }

        self.contentTextview.setEmotionAttributeText(model.text ?? "", darkMode: false)
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        
        //        self.namelabel.isHidden = true
        //        self.bgtopConstraint.constant = cell.namelabel.isHidden == true ? 0 : 18
        
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
        if model.chatType == .p2p {
            bgtopConstraint.constant = 0
            namelabel.isHidden = true
        }
    }
    
    func blur(_ view: UIView) {
        let effect = UIBlurEffect(style: .light)
        let blurView = UIVisualEffectView(effect: effect)
        view.addSubview(blurView)
        blurView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    override func transitionToHide() {
//        var text = ""
//        self.contentTextview.text.count.times { time in
//            text += "＊"
//        }
//        self.contentTextview.setEmotionAttributeText(text, darkMode: false)
//        self.contentTextview.isUserInteractionEnabled = false
//        blur(self.namelabel)
//        self.blurView.isHidden = false
//        self.contentTextview.isHidden = true
//        transition()
    }
    
    override func transitionToShow() {
//        self.contentTextview.setEmotionAttributeText(model.text ?? "", darkMode: false)
//        self.contentTextview.isUserInteractionEnabled = true
//        self.blurView.isHidden = true
//        self.contentTextview.isHidden = false
//        transition()
    }
    
    func transition() {
        let transition = CATransition()
        transition.type = CATransitionType(rawValue: "cube")
        transition.subtype = CATransitionSubtype.fromTop
        transition.duration = 0.2
        self.bubble.layer.add(transition, forKey: nil)
    }
    
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
        }
    }
    
    func addMenuItem() {
        let zhuanfaItem = UIMenuItem(title: "转发", action: #selector(zhuanfaAction))
        let menuVC = UIMenuController.shared
        menuVC.menuItems = [zhuanfaItem]
        menuVC.showMenu(from: self.bubble, rect: self.bubble.bounds)
    }
    
   
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(zhuanfaAction) {
            return true
        }
        if action == #selector(copy(_:)) {
            return true
        }
        if action == #selector(delete) {
            return true
        }
        return false
    }
    
    @objc override func delete(_ sender: Any?) {
        //删除
         self.delegate?.deleteDelegate(msg:model)
    }
    
    @objc func reportAction() {
        self.delegate?.reportDelegate(msg:model)
    }
    
    
    @objc func zhuanfaAction() {
        self.contentTextview.selectedTextRange = nil
        self.delegate?.zhuanfaDelegate(msg: model)
    }
}

extension ChatPureRightCell: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if URL.scheme == "http" || URL.scheme == "https" {
            let param = Param(url: URL)
            delegate?.openWebPage(param)
            return false
        }
        return true
    }
    
    @available(iOS 10.0, *)
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.scheme == "http" || URL.scheme == "https" {
            let param = Param(url: URL)
            delegate?.openWebPage(param)
            return false
        }
        return true
    }
}
